package com.tanhua.dubbo.api;


import com.sun.corba.se.impl.oa.poa.POAPolicyMediatorImpl_R_AOM;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class MovementApiImpl implements MovementApi {


    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveMovements(Movement movement) {

//        1、存储到圈子动态详情表中  movement_detail
        movement.setId(new ObjectId()); //mongodb的主键
        movement.setPid(idService.getNextId("movement_detail")); // 这个值是用在大数据推荐的 这个值Long  采用分布式id算法
        movement.setCreated(new Date().getTime());   // movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);
//        2、存储到自己的动态表中(相册表)   movement_mine_1
        MovementMine movementMine = new MovementMine();
        movementMine.setId(new ObjectId()); //主键
        movementMine.setMovementId(movement.getId()); //外键
        movementMine.setCreated(new Date().getTime());
        mongoTemplate.save(movementMine,"movement_mine_"+movement.getUserId());

//        3、查询当前登录人的朋友  mongo命令  db.getCollection('friend').find({userId:1})
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
//       4、 把这个圈子动态的id放到当前用户所有朋友的 movement_friend表中
/*        如果当前登录人的朋友是 2号 3号 4号 5号用户
                存储到当前登录人朋友的时间线表中
                movement_friend_2
                 movement_friend_3
                 movement_friend_4
                movement_friend_5*/
        for (Friend friend : friendList) {
            MovementFriend movementFriend = new MovementFriend();
            movementFriend.setId(new ObjectId());
            movementFriend.setMovementId(movement.getId()); //圈子动态id
            movementFriend.setUserId(movement.getUserId());  //圈子的所属人id
            movementFriend.setCreated(new Date().getTime());
            mongoTemplate.save(movementFriend,"movement_friend_"+friend.getFriendId());
        }

        return movement.getId().toString();
    }

    @Override
    public PageResult queryFriendMovements(Long userId, Integer page, Integer pagesize) {
//        假如  当前登录人是2号用户 查询的表是 movement_friend_userId
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"created")); //最新发布的朋友圈排到上面
        query.limit(pagesize).skip( (page-1) *pagesize );
        List<MovementFriend> list = mongoTemplate.find(query, MovementFriend.class, "movement_friend_" + userId);

        long count = mongoTemplate.count(query,MovementFriend.class,"movement_friend_" + userId);
//        把list中的MovementFriend联查出一个一个的Movement

        List<Movement> movementList = new ArrayList<>();
        for (MovementFriend movementFriend : list) {
//            根据movementFriend中的movementID查询Movement详情
            Movement movement = mongoTemplate.findById(movementFriend.getMovementId(), Movement.class);
//            注意一个问题，因为目前表中有很多测试数据 导致根据movementFriend.getId()查不到Movement
            if(movement==null){
                continue;
            }
            movementList.add(movement);
        }
//        关联movement_detail表中的数据
        return new PageResult(page,pagesize,(int)count,movementList);
    }

    @Override
    public PageResult queryRecommendMovements(Long userId, Integer page, Integer pagesize) {
//        db.getCollection('recommend_movement').find({userId:1}).limit(10).skip(0).sort({score:-1})
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC,"created")); //最新发布的朋友圈排到上面
        query.limit(pagesize).skip( (page-1) *pagesize );
        List<RecommendMovement> list = mongoTemplate.find(query, RecommendMovement.class);
        long count = mongoTemplate.count(query,RecommendMovement.class);

        List<Movement> movementList = new ArrayList<>();
        for (RecommendMovement recommendMovement : list) {
//            根据movementFriend中的movementID查询Movement详情
            Movement movement = mongoTemplate.findById(recommendMovement.getMovementId(), Movement.class);
//            注意一个问题，因为目前表中有很多测试数据 导致根据movementFriend.getId()查不到Movement
            if(movement==null){
                continue;
            }
            movementList.add(movement);
        }

        return new PageResult(page,pagesize,(int)count,movementList);
    }

    @Override
    public PageResult queryMySelfMovements(Long userId, Integer page, Integer pagesize) {
//        查询自己发布的动态 相册集表 movement_mine_USERID
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"created")); //最新发布的朋友圈排到上面
        query.limit(pagesize).skip( (page-1) *pagesize );
        List<MovementMine> list = mongoTemplate.find(query, MovementMine.class, "movement_mine_" + userId);
        long count = mongoTemplate.count(query,MovementMine.class,"movement_mine_" + userId);
//        把list中的MovementMine联查出一个一个的Movement

        List<Movement> movementList = new ArrayList<>();
        for (MovementMine movementMine : list) {
//            根据MovementMine中的movementID查询Movement详情
            Movement movement = mongoTemplate.findById(movementMine.getMovementId(), Movement.class);
//            注意一个问题，因为目前表中有很多测试数据 导致根据MovementMine.getMovementId()查不到Movement
            if(movement==null){
                continue;
            }
            movementList.add(movement);
        }
//        关联movement_detail表中的数据
        return new PageResult(page,pagesize,(int)count,movementList);
    }

    @Override
    public Movement queryMovementById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    @Override
    public PageResult queryUserMovements(Integer page, Integer pagesize, Long userId, Integer state) {
        //        查询指定用户发布的动态 相册集表 movement_mine_userId
        Query query = new Query();
//        Criteria.where("userId").is(userId).and("state").is(state)
        if(state!=null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        if(userId!=null){
            query.addCriteria(Criteria.where("userId").is(userId));
        }


        query.with(Sort.by(Sort.Direction.DESC,"created")); //最新发布的朋友圈排到上面
        query.limit(pagesize).skip( (page-1) *pagesize );
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query,Movement.class);
//        关联movement_detail表中的数据
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public void updateStateById(String movementId, Integer state) {

        Query query = new Query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);

    }
}